﻿using System;
using UnityEngine;

[RequireComponent(typeof(Renderer))]
public class RendererFader : MonoBehaviour
{
    public float destAlpha = 0.2f;
    private Material initialMat;
    private Renderer ren;
    public Shader shader;
    public float speed = 5f;
    private Material transparentMat;

    private void OnBecameInvisible()
    {
        this.ren.sharedMaterial = this.initialMat;
    }

    private void Start()
    {
        this.ren = base.GetComponent<Renderer>();
        this.initialMat = this.ren.sharedMaterial;
        this.transparentMat = UnityEngine.Object.Instantiate<Material>(this.ren.sharedMaterial);
        this.transparentMat.shader = this.shader;
    }

    private void Update()
    {
        Color color = this.transparentMat.color;
        color.a = Mathf.Lerp(color.a, this.destAlpha, Time.deltaTime * this.speed);
        this.transparentMat.color = color;
        if (color.a < 0.99f)
        {
            this.ren.sharedMaterial = this.transparentMat;
        }
    }
}

